﻿using Collections.Pooled;
using FieldTools.Client.Command;
using FieldTools.Client.Model.Window;
using FieldTools.Client.Tools;
using FieldTools.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FieldTools.Client.ViewModel.Window
{
    /// <summary>
    /// 米游社相关
    /// </summary>
    public class MihoyoViewModel : NotificationObject, ISingletonDependency
    {
        /// <summary>
        /// 
        /// </summary>
        public MihoyoViewModel()
        {
            obj = CacheHelper.GetOrSetCache("MihoyoModel", new MihoyoModel());
            FastRequest = FastRequests.FirstOrDefault(x => x.MihoyoModel.BaseUrl == obj.BaseUrl && x.MihoyoModel.PostUrl == obj.PostUrl, FastRequests.FirstOrDefault()).MihoyoModel;
            //LogHelper.loginfo.Info($"米游社工具打开，装载参数：{obj.ToJson()}");
            ParseParms();
        }

        #region 实体
        MihoyoModel obj = new();
        private List<FastRequest> fastRequests = new()
        {
            new()
            {
                Title = "获取帖子数据",
                MihoyoModel = new()
                {
                    PostUrl = "/post/wapi/getPostFull",
                    Paramters = "gids:2\r\npost_id:23154702\r\nread:1",
                }
            },
            new()
            {
                Title = "获取官方资讯",
                MihoyoModel = new()
                {
                    PostUrl = "/post/wapi/getOfficialRecommendedPosts",
                    Paramters = "gids:2",
                }
            },
            new()
            {
                Title = "获取某帖子下的热门内容",
                MihoyoModel = new()
                {
                    PostUrl = "/post/wapi/semPosts",
                    Paramters = "gids:2\r\npost_id:23154702",
                }
            },
            new()
            {
                Title = "获取pc端广告",
                MihoyoModel = new()
                {
                    PostUrl = "/misc/wapi/getPCBanner",
                    Paramters = "gids:2",
                }
            },
            new()
            {
                Title = "获取榜单",
                MihoyoModel = new()
                {
                    PostUrl = "/post/wapi/getImagePostTopN",
                    Paramters = "forum_id:29",
                }
            },
            new()
            {
                Title = "获取板块内容",
                MihoyoModel = new()
                {
                    PostUrl = "/post/wapi/getForumPostList",
                    Paramters = "forum_id:29\r\nis_good:false\r\nis_hot:false\r\npage_size:20\r\nsort_type:1",
                }
            },
        };
        /// <summary>
        /// 快捷请求集合
        /// </summary>
        public List<FastRequest> FastRequests
        {
            get { return fastRequests; }
            set { fastRequests = value; this.RaisePropertyChanged(nameof(FastRequests)); }
        }

        private MihoyoModel fastRequest;
        /// <summary>
        /// 快捷请求
        /// </summary>
        public MihoyoModel FastRequest
        {
            get { return fastRequest; }
            set { fastRequest = value;
                BaseUrl = value.BaseUrl;
                PostUrl = value.PostUrl;
                Headers = value.Headers;
                Paramters = value.Paramters;
                RequestType = value.RequestType;
                NodePath = value.NodePath;
                OutPut = string.Empty;
                OutSource = string.Empty;
                this.RaisePropertyChanged(nameof(FastRequest)); }
        }


        /// <summary>
        /// 请求头
        /// </summary>
        public string Headers
        {
            get { return obj.Headers; }
            set { obj.Headers = value; CacheHelper.SetCache("MihoyoModel",obj); this.RaisePropertyChanged(nameof(Headers)); }
        }
        /// <summary>
        /// 基础请求地址
        /// </summary>
        public string BaseUrl
        {
            get { return obj.BaseUrl; }
            set { obj.BaseUrl = value; CacheHelper.SetCache("MihoyoModel", obj); this.RaisePropertyChanged(nameof(BaseUrl)); }
        }
        /// <summary>
        /// 基础请求地址
        /// </summary>
        public string? PostUrl
        {
            get { return obj.PostUrl; }
            set { obj.PostUrl = value; CacheHelper.SetCache("MihoyoModel", obj); this.RaisePropertyChanged(nameof(PostUrl)); }
        }
        /// <summary>
        /// 请求参数
        /// </summary>
        public string? Paramters
        {
            get { return obj.Paramters; }
            set { obj.Paramters = value; CacheHelper.SetCache("MihoyoModel", obj); ParseParms(); this.RaisePropertyChanged(nameof(Paramters)); }
        }
        private Dictionary<string, int>? requestTypes = new()
        {
            ["GET"] = 1,
            ["POST"] = 2,
        };
        /// <summary>
        /// 请求类型集合
        /// </summary>
        public Dictionary<string, int>? RequestTypes
        {
            get { return requestTypes; }
            set { requestTypes = value; this.RaisePropertyChanged(nameof(RequestTypes)); }
        }
        /// <summary>
        /// 请求类型
        /// </summary>
        public int RequestType
        {
            get { return obj.RequestType; }
            set { obj.RequestType = value; CacheHelper.SetCache("MihoyoModel", obj); this.RaisePropertyChanged(nameof(RequestType)); }
        }

        /// <summary>
        /// json节点查询
        /// </summary>
        public string? NodePath
        {
            get { return obj.NodePath; }
            set { obj.NodePath = value; CacheHelper.SetCache("MihoyoModel", obj); this.RaisePropertyChanged(nameof(NodePath)); }
        }

        private string outPut;
        /// <summary>
        /// 接口请求返回输出
        /// </summary>
        public string OutPut
        {
            get { return outPut; }
            set { outPut = value; this.RaisePropertyChanged(nameof(OutPut)); }
        }

        private Dictionary<string, string> gidsCollection = new()
        {
            ["崩坏学院2"] = "0",
            ["崩坏3"] = "1",
            ["原神"] = "2",
            ["未定事件簿"] = "3",
            ["崩坏星穹铁道"] = "4",
            ["绝区零"] = "5",
            ["大别野"] = "6",
        };
        /// <summary>
        /// 获取类型集合
        /// </summary>
        public Dictionary<string, string> GidsCollection
        {
            get { return gidsCollection; }
            set { gidsCollection = value; this.RaisePropertyChanged(nameof(GidsCollection)); }
        }


        private string? gids;
        /// <summary>
        /// 获取类型，0崩坏学园2，1崩坏3，2原神，3未定事件簿，4崩坏星穹铁道，5绝区零，6大别野
        /// </summary>
        public string? Gids
        {
            get { return gids; }
            set { gids = value; this.RaisePropertyChanged(nameof(Gids)); }
        }

        private string page = "";
        /// <summary>
        /// 分页页码
        /// </summary>
        public string Page
        {
            get { return page; }
            set { page = value; this.RaisePropertyChanged(nameof(Page)); }
        }

        private string pageSize;
        /// <summary>
        /// 分页大小
        /// </summary>
        public string PageSize
        {
            get { return pageSize; }
            set { pageSize = value; this.RaisePropertyChanged(nameof(PageSize)); }
        }

        private string postId;
        /// <summary>
        /// 帖子Id
        /// </summary>
        public string PostId
        {
            get { return postId; }
            set { postId = value; this.RaisePropertyChanged(nameof(PostId)); }
        }

        private Dictionary<string, string> sortTypeCollection = new()
        {
            ["最新回复"] = "1",
            ["最新发帖"] = "2",
            ["热门"] = "0",
        };
        /// <summary>
        /// 排序类型集合
        /// </summary>
        public Dictionary<string, string> SortTypeCollection
        {
            get { return sortTypeCollection; }
            set { sortTypeCollection = value; this.RaisePropertyChanged(nameof(SortTypeCollection)); }
        }

        private string sortType;
        /// <summary>
        /// 排序类型
        /// </summary>
        public string SortType
        {
            get { return sortType; }
            set { sortType = value; this.RaisePropertyChanged(nameof(SortType)); }
        }

        private Dictionary<string, string> forumIdCollection = new()
        {
            ["原神-酒馆"] = "26",
            ["原神-官方"] = "28",
            ["原神-同人图"] = "29",
            ["原神-攻略"] = "43",
            ["原神-COS"] = "49",
            ["原神-硬核"] = "50",
            ["未定事件簿-官方"] = "33",
            ["未定事件簿-律所"] = "37",
            ["未定事件簿-同人图"] = "38",
            ["未定事件簿-同人文"] = "42",
            ["绝区零-咖啡馆"] = "57",
            ["绝区零-官方"] = "58",
            ["绝区零-同人图"] = "59",
            ["崩坏学院2-学院"] = "30",
            ["崩坏学院2-官方"] = "31",
            ["崩坏学院2-反馈"] = "32",
            ["崩坏学院2-同人图"] = "40",
            ["崩坏学院2-攻略"] = "51",
            ["崩坏3-甲板"] = "1",
            ["崩坏3-同人图"] = "4",
            ["崩坏3-官方"] = "6",
            ["崩坏3-攻略"] = "14",
            ["崩坏3-同人文"] = "41",
            ["崩坏：星穹铁道-候车室"] = "52",
            ["崩坏：星穹铁道-官方"] = "53",
            ["崩坏：星穹铁道-同人图"] = "56",
            ["(暂未使用)-2"] = "2",
            ["(暂未使用)-3"] = "3",
            ["(暂未使用)-5"] = "5",
            ["(暂未使用)-7"] = "7",
            ["(暂未使用)-8"] = "8",
            ["(暂未使用)-9"] = "9",
            ["(暂未使用)-10"] = "10",
            ["(暂未使用)-11"] = "11",
            ["(暂未使用)-12"] = "12",
            ["(暂未使用)-13"] = "13",
            ["(暂未使用)-15"] = "15",
            ["(暂未使用)-16"] = "16",
            ["(暂未使用)-17"] = "17",
            ["(暂未使用)-18"] = "18",
            ["(暂未使用)-19"] = "19",
            ["(暂未使用)-20"] = "20",
            ["(暂未使用)-21"] = "21",
            ["(暂未使用)-22"] = "22",
            ["(暂未使用)-23"] = "23",
            ["(暂未使用)-24"] = "24",
            ["(暂未使用)-25"] = "25",
            ["(暂未使用)-27"] = "27",
            ["(暂未使用)-34"] = "34",
            ["(暂未使用)-35"] = "35",
            ["(暂未使用)-36"] = "36",
            ["(暂未使用)-39"] = "39",
            ["(暂未使用)-44"] = "44",
            ["(暂未使用)-45"] = "45",
            ["(暂未使用)-46"] = "46",
            ["(暂未使用)-47"] = "47",
            ["(暂未使用)-48"] = "48",
            ["(暂未使用)-54"] = "54",
            ["(暂未使用)-55"] = "55",
            ["(暂未使用)-60"] = "60"
        };
        /// <summary>
        /// 论坛板块Id集合
        /// </summary>
        public Dictionary<string, string> ForumIdCollection
        {
            get { return forumIdCollection; }
            set { forumIdCollection = value; this.RaisePropertyChanged(nameof(ForumIdCollection)); }
        }


        private string forumId;
        /// <summary>
        /// 论坛板块id
        /// </summary>
        public string ForumId
        {
            get { return forumId; }
            set { forumId = value; this.RaisePropertyChanged(nameof(ForumId)); }
        }



        private string OutSource { get; set; }

        #endregion

        #region 事件
        private BaseCommand request;
        /// <summary>
        /// 请求
        /// </summary>
        public BaseCommand Request
        {
            get
            {
                if (request == null)
                {
                    request = new BaseCommand(new Action<object>(o =>
                    {
                        if (!string.IsNullOrEmpty(BaseUrl) && !string.IsNullOrEmpty(PostUrl))
                        {
                            Dictionary<string, string> tempHeaders = GetParmsStr(Headers);
                            Dictionary<string, object> tempParms = GetParms(Paramters ?? "");
                            var result = HttpHelper.GetData(BaseUrl.RemoveEndChar('/')+"/"+PostUrl.RemoveStartChar('/'), tempParms, tempHeaders);
                            OutSource = result.FormatJsonString();
                            OutPut = OutSource;
                        }
                    }));
                }
                return request;
            }
        }

        private BaseCommand readJson;
        /// <summary>
        /// 读取json
        /// </summary>
        public BaseCommand ReadJson
        {
            get
            {
                if (readJson == null)
                {
                    readJson = new BaseCommand(new Action<object>(o =>
                    {
                        if (!string.IsNullOrEmpty(NodePath))
                        {
                            OutPut = OutSource.GetJsonNode(NodePath);
                        }
                    }));
                }
                return readJson;
            }
        }

        private BaseCommand generateParms;
        /// <summary>
        /// 生成请求参数
        /// </summary>
        public BaseCommand GenerateParms
        {
            get
            {
                if (generateParms == null)
                {
                    generateParms = new BaseCommand(new Action<object>(o =>
                    {
                        CompoundParms();
                    }));
                }
                return generateParms;
            }
        }

        private BaseCommand openCosTopN;
        /// <summary>
        /// 生成请求参数
        /// </summary>
        public BaseCommand OpenCosTopN
        {
            get
            {
                if (openCosTopN == null)
                {
                    openCosTopN = new BaseCommand(new Action<object>(o =>
                    {
                        var url = "https://bbs-api.mihoyo.com/post/wapi/getImagePostTopN";
                        //获取图集合
                        Dictionary<string, object> parms = new()
                        {
                            ["forum_id"] = 49
                        };
                        var pcs = GetForumPics(url, parms, "cos图", "原神今日cos榜");
                        if(pcs != null)
                        {
                            WindowManager.Show("PicsShowWindow", new PicsShowViewModel(pcs));
                        }
                        else
                        {
                            //LogHelper.logerror.Error($"从{url}接口库获取图片失败集合失败，请求参数：{parms.ToJson()}");
                            MessageBox.Show("资源获取失败，详情查看日志");
                        }
                    }));
                }
                return openCosTopN;
            }
        }
        #endregion

        #region 方法
        private static Dictionary<string, object> GetParms(string parms)
        {
            if (parms is null or "") return new();
            var result = new Dictionary<string, object>();
            var ps = parms.Split("\r\n");
            if (ps == null) ps = parms.Split("\n");
            foreach (var p in ps)
            {
                if(p.Any(x=>x==':'))
                {
                    var key = p.Split(":").First();
                    var value = p[(p.IndexOf(":")+1)..];

                    result.Add(key, value);
                }
            }
            return result;
        }
        private static Dictionary<string, string> GetParmsStr(string parms)
        {
            if (parms is null or "") return new();
            var result = new Dictionary<string, string>();
            var ps = GetParms(parms);
            foreach (var t in ps)
            {
                result.Add(t.Key, t.Value.ToString());
            }
            return result;
        }

        private void ParseParms()
        {
            if (string.IsNullOrEmpty(Paramters))
            {
                Gids = "";
                Page = "";
                PageSize = "";
                PostId = "";
                SortType = "";
                ForumId = "";
                return;
            }
            var parms = GetParmsStr(Paramters);
            foreach (var t in parms)
            {
                if(t.Key == "gids") Gids = t.Value;
                else if(t.Key == "page") Page = t.Value;
                else if(t.Key == "page_size") PageSize = t.Value;
                else if(t.Key == "post_id") PostId = t.Value;
                else if(t.Key == "sort_type") SortType = t.Value;
                else if(t.Key == "forum_id") ForumId = t.Value;
            }
        }
        private void CompoundParms()
        {
            var tempDic = new Dictionary<string, string>();
            if(!string.IsNullOrEmpty(Gids)) tempDic.Add("gids", Gids);
            if(!string.IsNullOrEmpty(Page)) tempDic.Add("page", Page);
            if(!string.IsNullOrEmpty(PageSize)) tempDic.Add("page_size", PageSize);
            if(!string.IsNullOrEmpty(PostId)) tempDic.Add("post_id", PostId);
            if(!string.IsNullOrEmpty(SortType)) tempDic.Add("sort_type", SortType);
            if(!string.IsNullOrEmpty(ForumId)) tempDic.Add("forum_id", ForumId);
            if (!tempDic.Any()) Paramters = "";
            else
            {
                var tempParms = "";
                foreach(var t in tempDic)
                {
                    tempParms += t.Key + ":" + t.Value + (t.Key != tempDic.Last().Key ? "\r\n" : "");
                }
                Paramters = tempParms;
            }
        }
        /// <summary>
        /// 获取板块图片（可获取排行榜）
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parms">请求参数</param>
        /// <param name="title">自定义标题</param>
        /// <param name="from">自定义来源</param>
        /// <returns></returns>
        public static PooledList<Pic>? GetForumPics(string url, Dictionary<string, object> parms, string title="", string from="")
        {
            PooledList<Pic> list = new();
            //请求获取原始数据
            Dictionary<string, string> tempHeaders = GetParmsStr("Referer:https://bbs.mihoyo.com/");
            var result = HttpHelper.GetData(url, parms, tempHeaders);
            var tt = result.GetJsonNode("[data][list]");
            var os = tt.ToObject<List<object>>();
            int j = 0;
            for(int i = 0; i < os.Count; i++)
            {
                var imgsNode = result.GetJsonNode($"[data][list][{i}][image_list]");
                var subjectNode = result.GetJsonNode($"[data][list][{i}][post][subject]");
                var creatAt = result.GetJsonNode($"[data][list][{i}][post][created_at]");
                var nickname = result.GetJsonNode($"[data][list][{i}][user][nickname]");
                if (!string.IsNullOrEmpty(imgsNode))
                {
                    //双引号里面的内容
                    //Regex regex = new("(?i)(?<=\")(.*?)(?=\")");
                    var imgs = imgsNode.ToObject<List<object>>();
                    if (imgs.Any())
                    {
                        foreach (var img in imgs)
                        {
                            var jsonTemp = img.ToJson();
                            var im = jsonTemp.GetJsonNode("[url]");
                            var size = jsonTemp.GetJsonNode("[size]");
                            var height = jsonTemp.GetJsonNode("[height]");
                            var width = jsonTemp.GetJsonNode("[width]");
                            list.Add(
                                new()
                                {
                                    Title = string.IsNullOrEmpty(title) ? "未知"  : title,
                                    Subject = subjectNode,
                                    From = string.IsNullOrEmpty(from) ? "未知" : title,
                                    Index = ++j,
                                    CreatedBy = string.IsNullOrEmpty(nickname) ? "未知" :nickname,
                                    CreatedAt = string.IsNullOrEmpty(creatAt) ? "未知" : new DateTime(creatAt.ToLong()).ToShortDateString(),
                                    Height = string.IsNullOrEmpty(height) ? null : height.TryToInt(),
                                    Width = string.IsNullOrEmpty(width) ? null : width.TryToInt(),
                                    Size = string.IsNullOrEmpty(size) ? null : long.Parse(size),
                                    BitmapFrameE = new(im)
                                }
                            );
                        }
                    }
                }
            }
            //获取指定节点内容
            if (list.Any())return list;
            return null;
        }
        
        public void ShowPics(string url, string forum_id, string grids)
        {

        }
        #endregion
    }
}
